<template>
  <div>
    <el-card>
      <template #header>
        <h2>编辑用户</h2>
      </template>

      <el-form ref="refFrom" :label-width="80" :rules="rules" :model="form">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="form.password" />
        </el-form-item>
        <el-form-item label="确认密码" prop="cpassword">
          <el-input type="password" v-model="form.cpassword" />
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="form.phone" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-input v-model="form.role" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="save">确定</el-button>
          <el-button type="info" @click="$router.push({ name: 'UsersIndex' })">取消</el-button>
        </el-form-item>
      </el-form>

    </el-card>
  </div>
</template>
<script setup>
// eslint-disable-next-line import/no-extraneous-dependencies
import { ElMessage } from 'element-plus';

import { ref } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { UsersExistApi, editUserApi, getUserByIdApi } from '../../api/users';

const router = useRouter();
const route = useRoute();
const refFrom = ref(null);

const form = ref({
  username: '',
  phone: '',
  email: '',
  password: '',
  cpassword: '',
  role: '',
});

const olduser = ref({});

async function getUserById() {
  const res = await getUserByIdApi(route.query.id);
  const {
    username, email, phone, role, password,
  } = res.data.data;

  olduser.value = res.data.data;// 旧值

  form.value.username = username;
  form.value.email = email;
  form.value.phone = phone;
  form.value.role = role;
  form.value.password = password;
}
getUserById();

function valid(key, message) {
  return async (_, value, cb) => {
    if (!value || olduser.value[key] === value) {
      cb();
    } else {
      const res = await UsersExistApi(key, value);
      if (res.data.data === false) {
        cb();
      } else {
        cb(new Error(message));
      }
    }
  };
}

const rules = {
  username: [
    { required: true, trigger: 'change', message: '用户名必须填写' },
    {
      validator: (_, value) => /^[\w-]{4,16}$/.test(value), trigger: 'change', message: '用户名校验，4到16位（字母，数字，下划线，减号）',
    },
    {
      validator: valid('username', '用户名已存在'), trigger: 'blur',
    },
  ],
  password: [
    {
      validator: (_, value) => {
        if (!value) return true;
        return /^\S*(?=\S{6,})(?=\S*\d)(?=\S*[A-Z])(?=\S*[a-z])(?=\S*[!@#$%^&*? ])\S*$/.test(value);
      },
      trigger: 'change',
      message: '密码强度校验，最少6位，包括至少1个大写字母，1个小写字母，1个数字，1个特殊字符',
    },
  ],
  cpassword: [
    {
      validator: (_, value) => {
        if (!value) return true;
        return value === form.value.password;
      },
      trigger: 'change',
      message: '两次密码输入不一致',
    },
  ],
  phone: [
    { required: true, trigger: 'change', message: '手机必须填写' },
    { validator: (_, value) => /^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(value), trigger: 'change', message: '手机格式错误' },
    {
      validator: valid('phone', '手机已存在'),
      trigger: 'blur',
    },
  ],
  email: [
    { required: true, trigger: 'change', message: '邮箱必须填写' },
    { validator: (_, value) => /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(value), trigger: 'change', message: '邮箱格式错误' },
    {
      validator: valid('email', '邮箱已存在'),
      trigger: 'blur',
    },
  ],
  role: [
    { required: true, trigger: 'change', message: '角色必须填写' },
  ],
};

async function save() {
  try {
    await refFrom.value.validate();
    const data = {};
    if (form.value.username !== olduser.value.username) {
      data.username = form.value.username;
    }
    if (form.value.phone !== olduser.value.phone) {
      data.phone = form.value.phone;
    }
    if (form.value.email !== olduser.value.email) {
      data.email = form.value.email;
    }
    if (form.value.role !== olduser.value.role) {
      data.role = form.value.role;
    }
    if (form.value.password) {
      data.password = form.value.password;
    }
    await editUserApi(route.query.id, data);
    router.push({ name: 'UsersIndex' });
    ElMessage.success('编辑成功');
  } catch (error) {
    // ElMessage.error('添加失败');
  }
}

</script>
